import datetime
import json
import time

from libs.comps.common.component import manager , TComponentManager , TComponent
from libs.comps.common.compSchedule import TCompSchedule
from libs.comps.common.compDB import TCompDB
import os.path
class TIotSchedule( TCompSchedule):
    def __init__(self , _manager):
        super().__init__(_manager)
    @property
    def db(self):
        res: TCompDB= None
        try:
            dbCode = self.compSettings['dbCode']
            res = self.manager.getComp("TCompDB" , dbCode)
        except Exception as er :
            self.manager.log(self , er)
        return res
    def init(self):
        try:
            dbResult = self.db.queryByKey('iot/scheduleInit',{})
            if dbResult['queryStatus'] == 1 :
                schedules = dbResult['datasetList'][0]
                vars = dbResult['datasetList'][1]
                self.info["variants"] ={}
                for v in vars:
                    vid = v['varId']
                    self.info['variants'][vid] = v
                for s in schedules:
                    shCode = s['shCode']
                    ats = s['ats']
                    shInfo = {
                        "schCode" : shCode ,
                        "schType" :s['timeType'] ,
                        "timeNum" :s['timeNum'] ,
                        "ats" :[x for x in ats.split(',') if x!=''],
                        "tag" :{
                            "shId" : s['shId']
                        } ,
                        "variants" : [x for x in vars if x['scheduleCode'] == shCode] ,
                        "info" : s
                    }
                    self.info['schedules'][shCode] = shInfo
                info = self.info
        except Exception as er:
            self.manager.log(self , er)
    def scheduleJob(self , schCode):
        try:
            schInfo = self.info['schedules'][schCode]
            pk = schInfo['info']['patternKey']
            pv = schInfo['info']['patternValue']
            flag = pk == '' or (
                ( pk!='' ) and
                ( pv!='' ) and
                datetime.datetime.now().strftime(pk) == pv
            )
            if flag :
                variants = schInfo['variants']
                for var in variants:
                    funCode = var['funCode']
                    dtuCode = var['dtuCode']
                    meterCode = var['meterCode']
                    varCode = var['varCode']
                    fn = f"/datas/schedule/task/{funCode}/{dtuCode}/task_{meterCode}_{varCode}.json"
                    if not  os.path.exists(fn):
                        dirName = os.path.dirname(fn)
                        if not os.path.exists(dirName):
                            os.makedirs(dirName, 0x777)
                        with open(fn , 'w' , encoding='utf-8') as f :
                            f.write(json.dumps(var , ensure_ascii=False))
                            f.flush()
        except Exception as er:
            self.manager.log(self , er)

manager.registCompType("TIotSchedule", TIotSchedule)